package com.accesshollywood.grfxOrdering.panels;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.TransferHandler;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.jdesktop.swingx.VerticalLayout;

import com.accesshollywood.components.BasicPopupMenu;
import com.accesshollywood.components.EditableListWithPopup;
import com.accesshollywood.components.EditableListWithPopup.EditableListModel;
import com.accesshollywood.components.HasPopupMenu;
import com.accesshollywood.grfxOrdering.basics.STATE;
import com.accesshollywood.grfxOrdering.basics.Users;
import com.accesshollywood.indexables.AbstractIndexedSet;
import com.accesshollywood.indexables.GrfxOrder;
import com.accesshollywood.indexables.User;
import com.accesshollywood.indexables.items.FootageIndexed;
import com.accesshollywood.indexables.items.StillIndexed;
import com.accesshollywood.p2p.P2P;
import com.accesshollywood.prefs.Prefs;

public class DragNDropPanel extends AbstractTitledPanel implements HasPopupMenu {
	public enum DROP {
		STILLS,
		FOOTAGE
	}

	public String					title	= "";
	public GrfxOrder				grfxOrder;
	protected JComponent			parent;
	// public EditableOneColumnTable table;
	public EditableListWithPopup	list;
	public DROP						drop;
	public String					dropString;

	public DragNDropPanel(GrfxOrder grfxOrder, JComponent parent, boolean useApproval, DROP drop) {
		super();
		this.grfxOrder = grfxOrder;
		this.parent = parent;
		this.drop = drop;
	}

	public void createPanel(AbstractIndexedSet indexedSet) {

		setAlignmentX(Component.LEFT_ALIGNMENT);
		setAlignmentY(Component.TOP_ALIGNMENT);
		// setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
		setLayout(new VerticalLayout());
		int h = 1;

		//EditableListModel model = new EditableListModel();
		//if (grfxOrder != null) {
		//	model.create(indexedSet, grfxOrder.getAssignedUsers());
		//}

		switch (drop) {
			case STILLS:
				// table = new EditableOneColumnTable(this, "still", "description", "idStill", "stillList", "idStill", "idStillList", "path", listing.id, Prefs.PixelSize.stillList.get(), true);
				list = new EditableListWithPopup(createModel(indexedSet, grfxOrder.getAssignedUsers()), Prefs.PixelSize.stillList.get(), StillIndexed.class);
				h = (list.getModel().getSize() + 1) * Prefs.PixelSize.stillList.get() + 5;
				break;
			case FOOTAGE:
				// table = new EditableOneColumnTable(this, "footage", "description", "idFootage", "footageList", "idFootage", "idFootageList", "path", listing.id, Prefs.PixelSize.footageList.get(), true);
				list = new EditableListWithPopup(createModel(indexedSet, grfxOrder.getAssignedUsers()), Prefs.PixelSize.footageList.get(), FootageIndexed.class);
				h = (list.getModel().getSize() + 1) * Prefs.PixelSize.footageList.get() + 5;
				break;
		}
		list.setAlignmentX(Component.LEFT_ALIGNMENT);

		list.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

		setupPopup();

		JScrollPane scrollPane = new JScrollPane(list);
		scrollPane.setPreferredSize(new Dimension(275, h));
		scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);

		add(scrollPane);
		// add(buttonAndListModel);

		// addClickListener();

		// allButtons.add(buttonAndListModel);
		OrderTree2.setBackgroundIfReady(DragNDropPanel.this, STATE.APPROVED);
	}

	public EditableListModel createModel(AbstractIndexedSet set, ArrayList<User> permittedUsers){
		return set.toEditableListModel();
	}
	
	public void setupPopup() {
		boolean permission = false;
		switch (drop) {
			case STILLS:
				permission = Users.currentUser.canEditStills(grfxOrder);
				break;
			case FOOTAGE:
				permission = Users.currentUser.canEditFootage(grfxOrder);
				break;
		}
		if (permission) {
			list.popup.popupItems = EnumSet.of(
					BasicPopupMenu.POPUP_ITEMS.ADD,
					BasicPopupMenu.POPUP_ITEMS.EDIT,
					BasicPopupMenu.POPUP_ITEMS.DELETE,
					BasicPopupMenu.POPUP_ITEMS.OPEN_FOLDER,
					BasicPopupMenu.POPUP_ITEMS.CLEAR_FOLDER
					);
		} else {
			list.popup.popupItems = EnumSet.of(
					BasicPopupMenu.POPUP_ITEMS.OPEN_FOLDER
					);
		}
		list.setupPopup();
	}

	public class MyListSelectionListener implements ListSelectionListener {
		@Override
		public void valueChanged(ListSelectionEvent e) {
			ArrayList listSelection = new ArrayList();
			/*
			 * if (table.getColumnSelectionAllowed() && !table.getRowSelectionAllowed()) {
			 * // Column selection is enabled
			 * // Get the indices of the selected columns
			 * int[] vColIndices = table.getSelectedColumns();
			 * } else if (!table.getColumnSelectionAllowed()
			 * && table.getRowSelectionAllowed()) {
			 */
			// Row selection is enabled
			// Get the indices of the selected rows

			int[] rowIndices = list.getSelectedIndices();

			for (int i = 0; i < rowIndices.length; i++) {
				listSelection.add(list.getModel().getElementAt(rowIndices[i]));
			}
			/*
			 * } else if (table.getCellSelectionEnabled()) {
			 * // Individual cell selection is enabled
			 * // In SINGLE_SELECTION mode, the selected cell can be retrieved
			 * // using
			 * table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			 * int rowIndex = table.getSelectedRow();
			 * int colIndex = table.getSelectedColumn();
			 * // In the other modes, the set of selected cells can be
			 * // retrieved using
			 * table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
			 * table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			 * // Get the min and max ranges of selected cells
			 * int rowIndexStart = table.getSelectedRow();
			 * int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
			 * int colIndexStart = table.getSelectedColumn();
			 * int colIndexEnd = table.getColumnModel().getSelectionModel().getMaxSelectionIndex();
			 * // Check each cell in the range
			 * for (int r = rowIndexStart; r <= rowIndexEnd; r++) {
			 * for (int c = colIndexStart; c <= colIndexEnd; c++) {
			 * if (table.isCellSelected(r, c)) {
			 * tableSelection.add(table.getModel().getValueAt(r, c));
			 * }
			 * }
			 * }
			 * }
			 * // buttonAndListModel.selectedValues = tableSelection.toArray();
			 */
		}
	}

	public void makeDragAndDrop(DROP drop) {
		this.drop = drop;
		setTransferHandler(new FSTransfer());
	}

	public String getUNCpath(File f) {
		String filePath = f.getAbsolutePath();
		try {
			Runtime runTime = Runtime.getRuntime();
			Process process;
			process = runTime.exec("net use");
			InputStream inStream = process.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inStream);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String line = null;
			String[] components = null;
			while (null != (line = bufferedReader.readLine())) {
				components = line.split("\\s+");
				if ((components.length > 2) && (components[1].equals(filePath.substring(0, 2)))) {
					filePath = filePath.replace(components[1], components[2]);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filePath;
	}

	// public void setTitleBorder(String str) {
	// setBorder(new TitledBorder(new EtchedBorder(), str));
	// }

	public class FSTransfer extends TransferHandler {
		public boolean importData(TransferHandler.TransferSupport support) {
			String UNCfilePath = "";
			Transferable t = support.getTransferable();
			DataFlavor[] df = support.getDataFlavors();
			DataFlavor listFlavor = null;
			DataFlavor objectFlavor = null;
			DataFlavor readerFlavor = null;

			List data;
			/*
			 * for (int f = 0; f < df.length; f++) {
			 * System.out.println("  " + df[f]);
			 * if (df[f].isFlavorJavaFileListType()) {
			 * listFlavor = df[f];
			 * }
			 * if (df[f].isFlavorSerializedObjectType()) {
			 * objectFlavor = df[f];
			 * }
			 * if (df[f].isRepresentationClassReader()) {
			 * readerFlavor = df[f];
			 * }
			 * }
			 */
			DataFlavor bestTextFlavor = DataFlavor.selectBestTextFlavor(df);
			if (bestTextFlavor == null) {
				try {
					data = (List) t.getTransferData(DataFlavor.javaFileListFlavor);

					Iterator i = data.iterator();
					while (i.hasNext()) {
						File f = (File) i.next();

						UNCfilePath = getUNCpath(f);
					}
				} catch (UnsupportedFlavorException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				dropString = UNCfilePath;
			} else {
				BufferedReader br = null;
				String line = null;
				String lines = "";
				if (bestTextFlavor != null) {
					System.out.println("Best text flavor: " + bestTextFlavor.getMimeType());
					System.out.println("Content:");
					Reader r;
					try {
						r = bestTextFlavor.getReaderForText(t);
						br = new BufferedReader(r);
						line = br.readLine();
						while (line != null) {
							System.out.println(line);
							lines += line;
							line = br.readLine();
						}
						br.close();
						String link = "";
						if (lines.contains("href=\"")) {
							link = lines.split("href=\"")[1];
							link = link.split("\">")[0];
						} else {
							link = lines;
						}
						dropString = link;
					} catch (UnsupportedFlavorException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			switch (drop) {
				case STILLS:
					setLink(dropString);
					refreshTitle();
					((EditableListModel) list.getModel()).setExtraData(dropString);
					// GFXSQL.setStillListPath(UNCfilePath, table.getModel().listID);
					OrderTree2.setBackgroundIfReady(DragNDropPanel.this, STATE.APPROVED);
					break;
				case FOOTAGE:
					setLink(dropString);
					refreshTitle();
					// GFXSQL.setFootageListPath(dropString, ((EditableListModel)list.getModel()).listID);
					OrderTree2.setBackgroundIfReady(DragNDropPanel.this, STATE.APPROVED);
					break;
			}

			P2P.refreshPeers(new int[] { grfxOrder.getId() });

			return true;
		}

		public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
			if (comp instanceof DragNDropPanel) {
				for (int i = 0; i < transferFlavors.length; i++) {
					DataFlavor html = transferFlavors[i];
					if (transferFlavors[i].equals(DataFlavor.javaFileListFlavor) || i == 1) {
						return true;
					}
				}
				return false;
			}
			return false;
		}
	}
}
